package com.xcx.services.impl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSONArray;
import com.xcx.bo.MosquitoRecordTime;
import com.xcx.bo.MosquitoUnlock;
import com.xcx.bo.MosquitoUnlockExample;
import com.xcx.common.dto.base.BaseDto;
import com.xcx.common.dto.base.BaseReq;
import com.xcx.common.dto.base.BaseResp;
import com.xcx.common.dto.req.SaveUserInfoReq;
import com.xcx.common.dto.req.UserLoginReq;
import com.xcx.common.dto.resp.UserLoginResp;
import com.xcx.common.enums.CommConfigParamKeyEnum;
import com.xcx.common.enums.IsValidEnum;
import com.xcx.common.services.MosquitoService;
import com.xcx.common.services.common.CommConfigService;
import com.xcx.common.services.common.CommUserService;
import com.xcx.common.utils.*;
import com.xcx.dao.MosquitoRecordTimeDao;
import com.xcx.dao.MosquitoUnlockDao;
import com.xcx.dto.QuerySharePhotoResp;
import com.xcx.dto.QueryUserUnlockReq;
import com.xcx.dto.RecordUseTimeReq;
import com.xcx.dto.RecordUseTimeResp;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class MosquitoServiceImpl implements MosquitoService {


    @Reference
    private CommUserService commUserService;

    @Reference
    private CommConfigService commConfigService;

    @Autowired
    private MosquitoRecordTimeDao recordTimeDao;

    @Autowired
    private MosquitoUnlockDao unlockDao;

    @Value("${wx.appId}")
    private String wxAppId;

    @Value("${wx.appSecret}")
    private String wxAppSecret;


    /**
     * 更新用户分享次数
     *
     * @param reqStr
     * @return
     */
    @Override
    public String updateUserShare(String reqStr) {
        log.info("updateUserShare.req:{}", reqStr);
        RecordUseTimeResp baseResp = new RecordUseTimeResp();
        try {
            CheckParamUtils.validateReqString(reqStr);
            QueryUserUnlockReq queryUserUnlockReq = BaseDto.fromJson(reqStr, QueryUserUnlockReq.class);
            CheckParamUtils.validateReqGson(queryUserUnlockReq);
            //判断用户是否解锁
            MosquitoUnlock mosquitoUnlock = queryUnlock(queryUserUnlockReq.getUserNo());
            if (mosquitoUnlock == null) {
                mosquitoUnlock = new MosquitoUnlock();
                mosquitoUnlock.setUnlockId(IdGenUtils.uuid());
                mosquitoUnlock.setUserNo(queryUserUnlockReq.getUserNo());
                mosquitoUnlock.setShareTicket(queryUserUnlockReq.getShareTicket());
                mosquitoUnlock.setIsUnlock(IsValidEnum.VALID_NO.getCode());
                mosquitoUnlock.setOnLoad(1);
                unlockDao.insert(mosquitoUnlock);
            } else {
                if (mosquitoUnlock.getShareTicket().contains(queryUserUnlockReq.getShareTicket())) {
                    baseResp.setIsUnlock(IsValidEnum.VALID_NO.getCode());
                    baseResp.setShareAgain(IsValidEnum.VALID_YES.getCode());
                } else {
                    mosquitoUnlock.setOnLoad(mosquitoUnlock.getOnLoad() + 1);
                    String maxShareNum = commConfigService.queryParamValue(CommConfigParamKeyEnum.MOSQUITO_MAX_SHARE_NUM);
                    if (mosquitoUnlock.getOnLoad() >= Integer.parseInt(maxShareNum)) {
                        mosquitoUnlock.setIsUnlock(IsValidEnum.VALID_YES.getCode());
                        mosquitoUnlock.setUpdatedDate(new Date());
                        baseResp.setIsUnlock(IsValidEnum.VALID_YES.getCode());
                    } else {
                        mosquitoUnlock.setIsUnlock(IsValidEnum.VALID_NO.getCode());
                        baseResp.setIsUnlock(IsValidEnum.VALID_NO.getCode());
                    }
                    unlockDao.updateByPrimaryKeySelective(mosquitoUnlock);
                }
            }
            baseResp.setOnLoad(mosquitoUnlock.getOnLoad());
            baseResp.buildDefaultSuccessResp(queryUserUnlockReq);
        } catch (Exception e) {
            ExceptionUtils.buildExceptionResp("MosquitoServiceImpl", reqStr, baseResp, e.getMessage(), e);
        }
        log.info("updateUserShare.resp:{}", baseResp.toString());
        return baseResp.toString();
    }

    /**
     * 查询分享图片列表
     *
     * @param reqStr
     * @return
     */
    @Override
    public String querySharePhoto(String reqStr) {
        log.info("querySharePhoto.req:{}", reqStr);
        QuerySharePhotoResp baseResp = new QuerySharePhotoResp();
        try {
            CheckParamUtils.validateReqString(reqStr);
            BaseReq baseReq = BaseDto.fromJson(reqStr, BaseReq.class);
            CheckParamUtils.validateReqGson(baseReq);
            String photoPathStr = commConfigService.queryParamValue(CommConfigParamKeyEnum.MOSQUITO_SHARE_PHOTO);
            if (StringUtils.isNotBlank(photoPathStr)) {
                JSONArray array = new JSONArray();
                String[] strs = photoPathStr.split(";");
                for (String str : strs) {
                    array.add(str);
                }
                baseResp.setPhotoPaths(array.toJSONString());
            }
            baseResp.buildDefaultSuccessResp(baseReq);

        } catch (Exception e) {
            ExceptionUtils.buildExceptionResp("MosquitoServiceImpl", reqStr, baseResp, e.getMessage(), e);
        }
        log.info("querySharePhoto.resp:{}", baseResp.toString());
        return baseResp.toString();
    }


    /**
     * 查询用户是否解锁
     *
     * @param reqStr
     * @return
     */
    @Override
    public String queryUserUnlock(String reqStr) {
        log.info("queryUserUnlock.req:{}", reqStr);
        RecordUseTimeResp recordUseTimeResp = new RecordUseTimeResp();
        try {
            CheckParamUtils.validateReqString(reqStr);
            QueryUserUnlockReq queryUserUnlockReq = BaseDto.fromJson(reqStr, QueryUserUnlockReq.class);
            CheckParamUtils.validateReqGson(queryUserUnlockReq);

            //判断用户是否解锁
            MosquitoUnlock mosquitoUnlock = queryUnlock(queryUserUnlockReq.getUserNo());
            if (mosquitoUnlock == null) {

                recordUseTimeResp.setIsOutTime(IsValidEnum.VALID_NO.getCode());
                recordUseTimeResp.setIsUnlock(IsValidEnum.VALID_NO.getCode());

                MosquitoRecordTime recordTime = recordTimeDao.selectByPrimaryKey(queryUserUnlockReq.getUserNo());
                if (recordTime != null) {
                    recordUseTimeResp.setTime(recordTime.getUseTime().toString());
                }

            } else if (StringUtils.equals(mosquitoUnlock.getIsUnlock(), IsValidEnum.VALID_YES.getCode())) {
                recordUseTimeResp.setIsUnlock(IsValidEnum.VALID_YES.getCode());
            } else {
                recordUseTimeResp.setIsOutTime(IsValidEnum.VALID_YES.getCode());
                recordUseTimeResp.setIsUnlock(IsValidEnum.VALID_NO.getCode());
            }

            recordUseTimeResp.buildDefaultSuccessResp(queryUserUnlockReq);
        } catch (Exception e) {
            ExceptionUtils.buildExceptionResp("MosquitoServiceImpl", reqStr, recordUseTimeResp, e.getMessage(), e);
        }
        log.info("queryUserUnlock.resp:{}", recordUseTimeResp.toString());
        return recordUseTimeResp.toString();
    }


    /**
     * 记录用户使用时长
     *
     * @param reqStr
     * @return
     */
    @Override
    public String recordUseTime(String reqStr) {
        log.info("recordUseTime.req:{}", reqStr);
        RecordUseTimeResp recordUseTimeResp = new RecordUseTimeResp();
        try {
            CheckParamUtils.validateReqString(reqStr);
            RecordUseTimeReq recordUseTimeReq = BaseDto.fromJson(reqStr, RecordUseTimeReq.class);
            CheckParamUtils.validateReqGson(recordUseTimeReq);

            String maxTime = commConfigService.queryParamValue(CommConfigParamKeyEnum.MOSQUITO_MAX_USE_TIME);

            int time = Integer.parseInt(recordUseTimeReq.getTime());
            //判断用户是否解锁
            MosquitoUnlock mosquitoUnlock = queryUnlock(recordUseTimeReq.getUserNo());
            if (mosquitoUnlock == null) {
                //未查到即为未解锁
                MosquitoRecordTime recordTime = recordTimeDao.selectByPrimaryKey(recordUseTimeReq.getUserNo());
                if (recordTime == null) {
                    recordTime = new MosquitoRecordTime();
                    recordTime.setUserNo(recordUseTimeReq.getUserNo());
                    recordTime.setUseTime(time);
                    recordTimeDao.insert(recordTime);

                } else {
                    recordTime.setUseTime(time);
                    recordTimeDao.updateByPrimaryKeySelective(recordTime);
                }

                //判断时间是否大于设置的免费可用时间
                if (recordTime.getUseTime() >= Integer.parseInt(maxTime)) {
                    recordUseTimeResp.setIsUnlock(IsValidEnum.VALID_NO.getCode());
                    recordUseTimeResp.setIsOutTime(IsValidEnum.VALID_YES.getCode());
                } else {
                    recordUseTimeResp.setIsOutTime(IsValidEnum.VALID_NO.getCode());
                    recordUseTimeResp.setIsUnlock(IsValidEnum.VALID_NO.getCode());
                }
                recordUseTimeResp.setTime(recordTime.getUseTime().toString());
            } else if (StringUtils.equals(mosquitoUnlock.getIsUnlock(), IsValidEnum.VALID_YES.getCode())) {
                recordUseTimeResp.setIsUnlock(IsValidEnum.VALID_YES.getCode());
            }

            recordUseTimeResp.buildDefaultSuccessResp(recordUseTimeReq);

        } catch (Exception e) {
            ExceptionUtils.buildExceptionResp("MosquitoServiceImpl", reqStr, recordUseTimeResp, e.getMessage(), e);
        }
        log.info("recordUseTime.resp:{}", recordUseTimeResp.toString());
        return recordUseTimeResp.toString();
    }


    private MosquitoUnlock queryUnlock(String userNo) {
        MosquitoUnlockExample example = new MosquitoUnlockExample();
        example.createCriteria()
                .andUserNoEqualTo(userNo);
        List<MosquitoUnlock> lst = unlockDao.selectByExample(example);
        return CollectionsUtils.isEmpty(lst) && lst.size() == 0 ? null : lst.get(0);
    }


    /**
     * 用户登录
     *
     * @param reqStr
     * @return
     */
    @Override
    public String userLogin(String reqStr) {
        log.info("userLogin.req:{}", reqStr);
        UserLoginResp UserLoginResp = new UserLoginResp();
        try {
            CheckParamUtils.validateReqString(reqStr);
            UserLoginReq userLoginReq = BaseDto.fromJson(reqStr, UserLoginReq.class);
            userLoginReq.setAppId(wxAppId);
            userLoginReq.setSecret(wxAppSecret);
            CheckParamUtils.validateReqGson(userLoginReq);
            UserLoginResp = commUserService.userLogin(userLoginReq);
            UserLoginResp.buildDefaultSuccessResp(userLoginReq);
        } catch (Exception e) {
            ExceptionUtils.buildExceptionResp("MosquitoServiceImpl", reqStr, UserLoginResp, e.getMessage(), e);
        }
        log.info("userLogin.resp:{}", UserLoginResp.toString());
        return UserLoginResp.toString();
    }

    /**
     * 保存用户信息
     *
     * @param reqStr
     * @return
     */
    @Override
    public String saveUserInfo(String reqStr) {
        log.info("saveUserInfo.req:{}", reqStr);
        BaseResp baseResp = new BaseResp();
        try {
            CheckParamUtils.validateReqString(reqStr);
            SaveUserInfoReq saveUserInfoReq = BaseDto.fromJson(reqStr, SaveUserInfoReq.class);
            CheckParamUtils.validateReqGson(saveUserInfoReq);
            baseResp = commUserService.saveUserInfo(saveUserInfoReq);
            baseResp.buildDefaultSuccessResp(saveUserInfoReq);
        } catch (Exception e) {
            ExceptionUtils.buildExceptionResp("MosquitoServiceImpl", reqStr, baseResp, e.getMessage(), e);
        }
        log.info("saveUserInfo.resp:{}", baseResp.toString());
        return baseResp.toString();
    }


}
